/**
 * Copyright (C)  Gadglet .
 *
 * This file is part of Gadglet
 *
 * Gadglet is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Gadglet is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Gadglet. If not, see <http://www.gnu.org/licenses/>.
 */

package com.gadglet.data;

import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.jdo.annotations.Extension;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import com.gadglet.data.utils.DomainAccountStatus;
import com.gadglet.data.utils.PMF;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

/**
 * Persistence class for Google Apps Domain Account.
 * The class is used WITHOUT App Engine NameSpace, any access must handle 
 * existing request NameSpace
 *
 */

@PersistenceCapable
public class DomainAccount {
	@PrimaryKey
	@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
	@Extension(vendorName = "datanucleus", key = "gae.encoded-pk", value = "true")
	private String accountId;
	
	
	@Persistent
	private Date creation;
	
	@Persistent
	private String  openIDAuthDomain;

	@Persistent
	private int status;
	
	@Persistent
	private int maxUsers;
	

	@Persistent
	private String creator;
	
	
	@Persistent
	private boolean allowUsersSelfActivation;
	
	public String getCreator() {
		return creator;
	}
	
	public int getMaxUsers() {
		return maxUsers;
	}

	public void setMaxUsers(int maxUsers) {
		this.maxUsers = maxUsers;
	}

	public boolean isAllowUsersSelfActivation() {
		return allowUsersSelfActivation;
	}

	void setAllowUsersSelfActivation(boolean allowUsersSelfActivation) {
		this.allowUsersSelfActivation = allowUsersSelfActivation;
	}

	public int getStatus() {
		return status;
	}

	public void setStatus(int status) {
		this.status = status;
	}

	
	public String getAccountId() {
		return accountId;
	}

	public Date getCreation() {
		return creation;
	}

	public String getName() {
		return openIDAuthDomain;
	}
	
	DomainAccount(int maxActiveUsers){
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		
		this.openIDAuthDomain =  user.getAuthDomain();
		this.creation = new Date();
		this.status = DomainAccountStatus.ACTIVE.getAccountStatus();
		if(maxActiveUsers>0)
			this.maxUsers = maxActiveUsers;
		else	
			this.maxUsers = 10;
		
		this.allowUsersSelfActivation = true;
		this.creator = user.getUserId();
		
	}
	
	/**
	 * @return the number of existing active users for this Domain account
	 */
	public int getDomainActiveUsersNum(){
		int num = 0;
		Logger log = Logger.getLogger("DomainAccount");
		PersistenceManager pm = PMF.get().getPersistenceManager();
		pm.currentTransaction().begin();
		Query query = pm.newQuery(DomainUser.class);
		try {

			query.setFilter("accountId == nameParam");
			query.declareParameters("String nameParam");
		
			num= ((List)query.execute(this.getAccountId())).size();
		
		} catch (Exception e) {
			log.warning(e.getMessage());
		} finally {
			 if (pm.currentTransaction().isActive()) 
			        pm.currentTransaction().rollback();
			
			 pm.close();
		}
		
		return num;
	}
	
	/**
	 * Save DomainAccount in the DataStore
	 * @return 
	 * @throws Exception
	 */
	DomainAccount save() throws Exception {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		pm.currentTransaction().begin();
		DomainAccount savedItem = null;
		try {
			savedItem = pm.makePersistent(this);
			pm.currentTransaction().commit();
		} catch (Exception e) {
			throw e;
		} finally {
			 if (pm.currentTransaction().isActive()) 
			        pm.currentTransaction().rollback();
		
			 pm.close();
		}
		return savedItem;
	}

}
